angular.module("ui.ssnau.waitable", [])
.directive("waitable", function(){
    var html = "<div class='waitable-container' style='position:fixed;z-index:9999;background:rgba(200,200,200,0.4);{{css}}'>" +
        "<div class='waitable-center'>" +
        "<i class='icon-spinner icon-spin'></i>" + "&nbsp;&nbsp;<span>{{info}}</span>" +
        "</div>" +
        "</div>";


    return {
        restrict: "A",
        link: function(scope, elem, attr) {
            var bindVar = attr.waitable,
                infoText = attr.waitableInfo,
                waitableCss = attr.waitableCss;

            var container = null;//放在这里是因为，同一个页面可以有多个waitable元素，因此container属于每个waitable的私有元素
            function showWating(elem, info, waitableCss) {
                hideWaiting();

                var elem = $(elem);
                var offset = elem.offset(),
                    dems   = {width: elem.width(), height: elem.height()};

                container = $(html.replace("{{info}}", info ? info : text).replace("{{css}}", waitableCss ? waitableCss : ''));
                container.css("top", offset.top + 'px');
                container.css("left", offset.left + 'px');
                container.css("width",dems.width + 'px');
                container.css("height", dems.height + 'px');
                container.css("lineHeight", dems.height + 'px');
                container.css("textAlign", 'center');

                container.appendTo(document.body);
                container.show();
            }

            function hideWaiting() {
                if (container) {
                    container.remove();
                    container = null;
                }
            }

            scope.$watch(bindVar, function(v){
                if (v) {
                    showWating(elem, infoText, waitableCss);
                } else {
                    hideWaiting();
                }
            })
        }
    }


});

/***
 * <div waitable="loadingNoteList" waitable-info="加载笔记列表" waitable-css="font-size:14px;opacity:.8"></div>
 * 一旦设置了$scope.loadingNoteList = true, Curtain便会显示出来。一旦$scope.loadingNoteList = false, 便立刻消失了。
 *
 **/